package com.Chat;

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatClient {
    private static final String S_Host = "localhost";// 服务器地址
    private static final int S_Port = 8080;// 服务器端口

    private Socket socket;// Socket接口
    private BufferedReader reader;// 输入流
    private PrintWriter writer;// 输出流
    private Scanner scanner;

    public static void main(String[] args) {
        ChatClient client = new ChatClient();
        client.start();
    }

    public void start() {
        try {
            socket = new Socket(S_Host, S_Port);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream(), true);//获取socket接口上的输出流，true表示自动刷新输出流，每次调用println()方法时，都会自动刷新输出流
            scanner = new Scanner(System.in);

            System.out.println("已连接到聊天服务器 " + S_Host + ":" + S_Port);
            System.out.println("输入 /help 查看可用命令");


            Thread messageReceiver = new Thread(new MessageReceiver());//创建一个消息接收线程
            messageReceiver.setDaemon(true);//setDaemon(true)：将当前线程设为守护线程，当所有非守护线程都结束运行时，守护线程也会自动结束运行。
            messageReceiver.start();//启动消息接收线程

            // 处理用户输入
            handleUserInput();

        } catch (IOException e) {
            System.err.println("连接服务器失败: " + e.getMessage());
        } finally {
            closeResources();//关闭资源
        }
    }

    private void receiveMessages() {
        try {
            String message;
            /*收到服务器发送的消息打印到控制台*/
            while ((message = reader.readLine()) != null) {//readLine()：从输入流中读取一行数据, 返回读取到的行。如果已到达流末尾，则返回 null
                System.out.println(message);
            }
        } catch (IOException e) {
            System.out.println("与服务器的连接已断开");
        }
    }

    private void handleUserInput() {
        while (true) {//循环实现用户输入消息处理
            System.out.print("> ");//提示输入位置
            String input = scanner.nextLine().trim();//trim()：去除字符串两端的空白字符

            if (input.equalsIgnoreCase("/quit")) {//输入/quit则退出聊天；equalsIgnoreCase：忽略大小写比较字符串
                System.out.println("断开连接...");
                break;
            }
            if (!input.isEmpty()) {
                writer.println(input);//发送用户输入的消息给服务器，让其处理
            }
        }
    }

    private void closeResources() {
        try {
            if (scanner != null) scanner.close();
            if (writer != null) writer.close();
            if (reader != null) reader.close();
            if (socket != null) socket.close();
        } catch (IOException e) {
            System.err.println("关闭资源时发生错误: " + e.getMessage());
        }
    }
    class MessageReceiver implements Runnable {
        @Override
        public void run() {
            receiveMessages();//调用接收消息的方法
        }
    }
}